//
//  WebView.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import SwiftUI
import WebKit

struct WebView: UIViewRepresentable {
    let url: URL
    let activity: Activity
    @EnvironmentObject var boxManager: BoxManager
    @Environment(\.dismiss) private var dismiss
    
    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        webView.navigationDelegate = context.coordinator
        
        // 恢复Cookie
        let currentBox = boxManager.getCurrentBox()
        CookieManager.shared.restoreCookies(for: currentBox.id, to: webView) {
            // 加载网页
            let request = URLRequest(url: self.url)
            webView.load(request)
        }
        
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {}
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, WKNavigationDelegate {
        var parent: WebView
        
        init(_ parent: WebView) {
            self.parent = parent
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            // 检查登录状态
            ScriptService.shared.checkLoginStatus(in: webView) { isLoggedIn in
                if isLoggedIn {
                    // 已登录，执行自动领取
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                        ScriptService.shared.executeAutoClaimScript(in: webView) { success in
                            if success {
                                print("自动领取成功")
                                // 保存Cookie
                                self.saveCookies(webView: webView)
                            }
                        }
                    }
                } else {
                    // 未登录，尝试QQ一键登录
                    print("检测到未登录，尝试QQ一键登录")
                    ScriptService.shared.executeQQLoginScript(in: webView) { loginSuccess in
                        if loginSuccess {
                            print("QQ登录按钮点击成功")
                        }
                    }
                }
            }
        }
        
        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            // 页面开始加载时保存Cookie
            saveCookies(webView: webView)
        }
        
        private func saveCookies(webView: WKWebView) {
            let currentBox = parent.boxManager.getCurrentBox()
            CookieManager.shared.saveCookies(for: currentBox.id) {
                print("Cookie保存完成")
            }
        }
    }
}

// WebView包装器
struct WebViewWrapper: View {
    let url: URL
    let activity: Activity
    
    var body: some View {
        WebView(url: url, activity: activity)
            .navigationTitle(activity.name)
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    ShareLink(item: url) {
                        Image(systemName: "square.and.arrow.up")
                    }
                }
            }
    }
}

#Preview {
    NavigationView {
        WebViewWrapper(url: URL(string: "https://dnf.qq.com/cp/a20250807index/indexm.html")!, 
                      activity: Activity.blackPrelude)
    }
}